package org.hit.burkun.cases.mapping;

import java.util.LinkedList;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.db.DBTypeConverter;
import org.hit.burkun.db.DBTypeConverter.DATATYPE;
import org.hit.burkun.file.FileProcessHelper;
import org.hit.burkun.file.FileProcessHelper.FILE_TYPE;
import org.hit.burkun.file.IDataLineProcesser;
import org.hit.burkun.mapping.IOnlineMappingProcessor.DBKEY;
import org.hit.burkun.util.GlobalData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 从string的提供的mapping数据中抽取string到gene id的mapping关系
 * 
 * @author burkun
 * 
 */
public class ImportStringGeneIDMapping {
	private FileProcessHelper fph;
	private final DBHelper dbh;
	private String[] insertFileds = new String[] { "dbkey1", "dbkey2",
			"dbkey1_type", "dbkey2_type", "come_from" };
	private String tbName;
	private static Logger logger = LoggerFactory
			.getLogger(ImportStringGeneIDMapping.class);

	public ImportStringGeneIDMapping(String fileName, String tbName,
			DBHelper dbh) {
		this.dbh = dbh;
		this.tbName = tbName;
		fph = new FileProcessHelper(fileName);
	}

	public void doImport() {
		// 保证从字典序的小向大映射
		final DBKEY from = DBKEY.GeneID;
		final DBKEY to = DBKEY.STRING;
		final String comefrom = "string id mapping";
		final LinkedList<String[]> data = new LinkedList<String[]>();
		fph.process(new IDataLineProcesser() {
			private int curLine = 0;

			@Override
			public String[] splitLine(String line) {
				return tabCsv(line);
			}

			@Override
			public String[] processItems(String[] items) {
				// items[0] = geneid
				// items[1] = string id
				// items[2] = from
				// items[3] = to
				// items[4] = comfrom
				String[] newI = new String[5];
				newI[0] = items[0];
				newI[1] = items[1];
				newI[2] = from.getTag();
				newI[3] = to.getTag();
				newI[4] = comefrom;
				return newI;
			}

			@Override
			public void doPostOutside(String[] items) {
				data.add(items);
			}

			@Override
			public void cleanUp() {
				// do nothing
			}

			@Override
			public String chooseLine(String line) {
				curLine++;
				if (curLine == 1) {
					return null;
				} else {
					return line;
				}
			}
		}, FILE_TYPE.PLAIN);
		importDB(data);
	}

	private void importDB(LinkedList<String[]> data) {
		logger.debug("save data in to " + tbName + "...");
		DATATYPE[] dataTypes = new DATATYPE[insertFileds.length];
		DBTypeConverter dataTypesCovert = new DBTypeConverter(dataTypes);
		dbh.connectionDB();
		dbh.insertBatch(tbName, insertFileds, data, dataTypesCovert);
		dbh.disconnection();
		logger.debug("save term data in to " + tbName + " done!");
	}

	public static void main(String[] args) {
		ImportStringGeneIDMapping importer = new ImportStringGeneIDMapping(
				GlobalData.getInstance().getStringGeneIdPath(),
				"dbkey_mapping", DBHelper.getLocalBioSearch());
		importer.doImport();
	}
}
